package cn.edu.cqu.bysj.services.hibernate;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.cqu.bysj.domains.TrainInfo;
import cn.edu.cqu.bysj.services.TrainInfoCRUD;

@Service("TrainInfoCRUDHibernate")
public class TrainInfoCRUDHibernate implements TrainInfoCRUD {

	private HibernateTemplate ht;
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		ht = new HibernateTemplate(sessionFactory);
	}
	
	@Transactional
	@Override
	public void add(TrainInfo trainInfo) {
		ht.save(trainInfo);
	}

	@Override
	public TrainInfo getByNo(String trainNo) {
		return ht.get(TrainInfo.class, trainNo);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TrainInfo> getAll() {
		List<TrainInfo> infos = (List<TrainInfo>) ht.find("from TrainInfo");
		return infos;
	}

	@Transactional
	@Override
	public void edit(String trainNo,TrainInfo trainInfo) {
		TrainInfo info = this.getByNo(trainNo);
		info.setEndStationName(trainInfo.getEndStationName());
		info.setStartStationName(trainInfo.getStartStationName());
		ht.update(info);
	}

	@Transactional
	@Override
	public void deleteByNo(String trainNo) {
		TrainInfo trainInfo = this.getByNo(trainNo);
		ht.delete(trainInfo);
	}

	@Transactional
	@Override
	public void deleteAll() {
		List<TrainInfo> infos = this.getAll();
		for (TrainInfo trainInfo : infos) {
			this.deleteByNo(trainInfo.getTrainNo());
		}
	}

}
